package com.syu.loopcure.compensator.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syu.loopcure.common.exception.CompensatorBusinessException;
import com.syu.loopcure.common.mybatis.mapper.ToolCureCompensatorMapper;
import com.syu.loopcure.compensator.aop.CompensatorLog;
import com.syu.loopcure.compensator.entity.ToolCureCompensator;
import com.syu.loopcure.compensator.enums.StatusEnum;
import com.syu.loopcure.compensator.service.ToolCureCompensatorService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 工具hydee-tool-core中补偿机制信息记录表 服务实现类
 * </p>
 *
 * @author zhucun
 * @since 2020-08-12
 */
@Service
public class ToolCureCompensatorServiceImpl extends ServiceImpl<ToolCureCompensatorMapper, ToolCureCompensator> implements ToolCureCompensatorService {
    
    private final static int RANDOM_TOP = 50;

    @Override
    public List<ToolCureCompensator> getCompensatorRecords() {
        Wrapper<ToolCureCompensator> queryWrapper = Wrappers.<ToolCureCompensator>lambdaQuery()
            .in(ToolCureCompensator::getStatus, Arrays.asList(StatusEnum.FAIL_NEED_COMPENSATOR.getCode(), StatusEnum.DOING_COMPENSATOR.getCode()));
        
        return super.list(queryWrapper);
    }
    
    @Override
    public List<ToolCureCompensator> findRecordByUniqueKey(String md5Code) {

        Wrapper<ToolCureCompensator> queryWrapper = Wrappers.<ToolCureCompensator>lambdaQuery()
            .eq(ToolCureCompensator::getMd5Code, md5Code);
        return super.list(queryWrapper);
    }
    
    @Override
    @CompensatorLog(maxRetryTimes=5,waitSeconds="10")
    public void test(String userId, String merCode) {
        int randomInt = (int) (Math.random()*(99)+1);
        if ( randomInt < RANDOM_TOP) {
            throw new CompensatorBusinessException(String.format("随机数：[%s]小于50,需要重试补偿",randomInt));
        }
    }

}
